<?php


namespace App\Http\Controllers\Admin\Game;


use App\Enums\GiftTypeEnum;
use App\Exceptions\BasicException;
use App\Http\Controllers\BaseController;
use App\Response\Response;
use Illuminate\Http\Request;


class GameGiftController extends BaseController
{
    //礼物下拉列表框
    /**
     * @api {get} /guessing/pro/gift 礼物下拉列表框
     * @apiVersion 0.1.0
     * @apiName 礼物下拉列表框
     * @apiGroup 霍克城堡 竞猜
     * @apiParam {Int}                     page  （选填）
     * @apiParam {Int}                     page_size  （选填）
     * @apiParam {String}                     name 礼物名称 （选填）
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": {
     * "total": 205,
     * "current_page": 1,
     * "last_page": 103,
     * "list": [
     * {
     * "id": 231,
     * "name": "纸飞机",
     * "picture": "http://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/admin_images/5f06f2a462e1e.png",
     * "price": 1314,
     * "special": "http://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/admin_images/5f06f2a78ec74.png",
     * "sort": 1314,
     * "type": 2,
     * "sold": 1,
     * "cardiac": 1314,
     * "frame_id": 28
     * },
     * {
     * "id": 349,
     * "name": "龙吟鹤唳",
     * "picture": "http://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/admin_images/5fad4a30215e8.png",
     * "price": 999999,
     * "special": "http://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/admin_images/5fad4a33eb507.svga",
     * "sort": 999,
     * "type": 1,
     * "sold": 1,
     * "cardiac": 999999,
     * "frame_id": 2
     * }
     * ]
     * }
     * }
     * @apiErrorExample 错误响应
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     */
    public function giftList(Request $request)
    {
        $data = $request->only(['page', 'page_size', 'name']);
        $data['page'] = $data['page'] ?? 1;
        $data['page_size'] = $data['page_size'] ?? 10;
        $data['name'] = $data['name'] ?? '';
        $where = [
            ['name', 'like', '%' . $data['name'] . '%'],
            ['sold', '=', 1],
            ['type', '=', GiftTypeEnum::getGiftType()['huoke']],
        ];
        $list = app('model_gift')
            ->where($where)
            ->orderBy('sort', 'desc')
            ->paginate($data['page_size'], ['*'], '', $data['page'])
            ->toArray();
        $result = [
            'total'        => $list['total'] ?? 0,
            'current_page' => $list['current_page'] ?? 1,
            'last_page'    => $list['last_page'] ?? 1,
            'list'         => $list['data'],
        ];

        return Response::sendData($result);
    }

    //添加兑换商品

    /**
     * @api {post} /guessing/pro 添加兑换商品
     * @apiVersion 0.1.0
     * @apiName 添加兑换商品
     * @apiGroup 霍克城堡 竞猜
     * @apiParam {Int}                     type 商品类型 0表示商品 1表示蓝钻（必填）
     * @apiParam {Int}                     product_id 礼物id type==0时必填 （选填）
     * @apiParam {Int}                     amount 蓝钻数量 当type==1时表必填（选填）
     * @apiParam {Int}                     price  价格（必填）
     * @apiParam {Int}                     stock   库存（必填）
     * @apiParam {Int}                     is_never 是否限时 0：是 1：否（必填）
     * @apiParam {Int}                     start_at 上架时间 （必填）
     * @apiParam {Int}                     end_at 下架时间 （必填）
     * @apiSuccessExample 成功响应
     * {"code":200,"data":true}
     * @apiErrorExample 错误响应
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     */


    public function addPro(Request $request)
    {
        $data = $request->only(['type', 'product_id', 'amount', 'price', 'stock', 'is_never', 'start_at', 'end_at']);
        $va = app('validator')->make($data, [
            'type'       => 'required|integer|in:0,1',//0表示gift 1表示balance
            'product_id' => 'integer|min:0',
            'amount '    => 'integer|min:0',
            'price'      => 'required|integer|min:1',
            'stock'      => 'required|integer|min:1|max:99999',
            'is_never'   => 'required|integer|in:0,1',
            'start_at'   => 'integer|min:0',
            'end_at'     => 'integer|min:0',
        ]);

        if ($va->fails()) {
            throw  new BasicException(10001, $va->errors()->first());
        }

        $data['type'] = $data['type'] == 0 ? 'gift' : 'balance';

        if ($data['is_never'] == 0) {//不是永久存在
            if (!isset($data['start_at']) || !isset($data['end_at']) || $data['start_at'] >= $data['end_at']) {
                throw  new BasicException(10001, '时间错误');
            }
        }

        $data['start_at'] = $data['is_never'] == 0 ? date('Y-m-d H:i:s', $data['start_at']) : null;
        $data['end_at'] = $data['is_never'] == 0 ? date('Y-m-d H:i:s', $data['end_at']) : null;

        if ($data['type'] == 'gift') {
            $data['amount'] = 0;
            $where = [
                ['id', '=', $data['product_id']],
                ['sold', '=', 1],
            ];
            $isHavePro = app('model_gift')->where($where)->where('id', GiftTypeEnum::getGiftType()['huoke'])->first();
            if (empty($isHavePro)) {
                throw  new BasicException(10001, '没有该礼品');
            }
        } else {
            $data['product_id'] = 0;
            if (!isset($data['amount']) || $data['amount'] <= 0) {
                throw  new BasicException(10001, '数量错误');
            }
        }


        $res = app('model_game_product_sku')->insert($data);
        if ($res) {
            return Response::sendData(true);
        } else {
            throw  new BasicException(10001, '插入失败');
        }
    }

    //编辑商品

    /**
     * @api {post} /guessing/pro 编辑商品
     * @apiVersion 0.1.0
     * @apiName 编辑商品
     * @apiGroup 霍克城堡 竞猜
     * @apiParam {Int}                     id 商品 （必填）
     * @apiParam {Int}                     type 商品类型 0表示商品 1表示蓝钻（必填）
     * @apiParam {Int}                     product_id 礼物id type==0时必填 （选填）
     * @apiParam {Int}                     amount 蓝钻数量 当type==1时表必填（选填）
     * @apiParam {Int}                     price  价格（必填）
     * @apiParam {Int}                     stock   库存（必填）
     * @apiParam {Int}                     is_never 是否限时 0：是 1：否（必填）
     * @apiParam {Int}                     start_at 上架时间 （必填）
     * @apiParam {Int}                     end_at 下架时间 （必填）
     * @apiSuccessExample 成功响应
     * {"code":200,"data":true}
     * @apiErrorExample 错误响应
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     */
    public function editPro(Request $request)
    {
        $data = $request->only(['id', 'type', 'product_id', 'amount', 'price', 'stock', 'is_never', 'start_at', 'end_at']);
        $va = app('validator')->make($data, [
            'id'         => 'required|integer',
            'type'       => 'required|integer|in:0,1',
            'product_id' => 'integer|min:0',
            'amount '    => 'integer|min:0',
            'price'      => 'required|integer|min:1',
            'stock'      => 'required|integer|min:1|max:99999',
            'is_never'   => 'required|integer|in:0,1',
            'start_at'   => 'integer|min:0',
            'end_at'     => 'integer|min:0',
        ]);
        if ($va->fails()) {
            throw  new BasicException(10001, $va->errors()->first());
        }
        $data['type'] = $data['type'] == 0 ? 'gift' : 'balance';

        if ($data['is_never'] == 0) {//不是永久存在
            if (!isset($data['start_at']) || !isset($data['end_at']) || $data['start_at'] >= $data['end_at']) {
                throw  new BasicException(10001, '时间错误');
            }
        }
        $data['start_at'] = $data['is_never'] == 0 ? date('Y-m-d H:i:s', $data['start_at']) : null;
        $data['end_at'] = $data['is_never'] == 0 ? date('Y-m-d H:i:s', $data['end_at']) : null;

        if ($data['type'] == 'gift') {
            $data['amount'] = 0;
            $where = [
                ['id', '=', $data['product_id']],
                ['sold', '=', 1],
            ];
            $isHavePro = app('model_gift')->where($where)->first();
            if (empty($isHavePro)) {
                throw  new BasicException(10001, '没有该礼品');
            }
        } else {
            $data['product_id'] = 0;
            if (!isset($data['amount']) || $data['amount'] <= 0) {
                throw  new BasicException(10001, '数量错误');
            }
        }

        $res = app('model_game_product_sku')->where('id', $data['id'])->update($data);
        if ($res) {
            return Response::sendData(true);
        } else {
            throw  new BasicException(10001, '修改失败');
        }
    }

    //礼物配置列表

    /**
     * @api {get} /guessing/pro 礼物配置列表
     * @apiVersion 0.1.0
     * @apiName 礼物配置列表
     * @apiGroup 霍克城堡 竞猜
     * @apiParam {Int}                     page  （选填）
     * @apiParam {Int}                     page_size  （选填）
     * @apiParam {String}                     name 礼物名称 （选填）
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": {
     * "total": 3,
     * "current_page": 1,
     * "last_page": 1,
     * "list": [
     * {
     * "id": 5,
     * "product_id": 231,//商品id type==gift时不为0
     * "type": "0",//0表示礼物 1表示蓝钻
     * "amount": 0,
     * "price": 1,//消耗
     * "stock": 12,//总数
     * "message": "",
     * "is_never": 1,
     * "start_at": null,
     * "end_at": null,
     * "created_at": "2021-08-18 10:21:14.174644",
     * "updated_at": "2021-08-18 10:35:49.154729",
     * "gift": {
     * "id": 231,
     * "name": "纸飞机"//礼物名称 当gift为null时 礼物名称为蓝钻
     * }
     * },
     * {
     * "id": 6,
     * "product_id": 0,
     * "type": "1",//0表示礼物 1表示蓝钻
     * "amount": 11,
     * "price": 1,
     * "stock": 12,
     * "message": "",
     * "is_never": 1,
     * "start_at": null,
     * "end_at": null,
     * "created_at": "2021-08-18 10:36:39.701820",
     * "updated_at": "2021-08-18 10:36:39.701820",
     * "gift": null
     * },
     * {
     * "id": 7,
     * "product_id": 584,
     * "type": "0",
     * "amount": 0,
     * "price": 1,
     * "stock": 12,
     * "message": "",
     * "is_never": 1,
     * "start_at": null,
     * "end_at": null,
     * "created_at": "2021-08-18 10:39:34.609252",
     * "updated_at": "2021-08-18 10:39:34.609252",
     * "gift": {
     * "id": 584,
     * "name": "形象设计"
     * }
     * }
     * ]
     * }
     * }
     * @apiErrorExample 错误响应
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     */
    public function proList(Request $request)
    {
        $data = $request->only(['page', 'page_size', 'name']);
        $va = app('validator')->make($data, [
            'page'      => 'integer|min:1',
            'page_size' => 'integer|min:1',
            'name'      => 'String|max:16',
        ]);
        if ($va->fails()) {
            throw  new BasicException(10001, $va->errors()->first());
        }
        $data['page'] = $data['page'] ?? 1;
        $data['page_size'] = $data['page_size'] ?? 10;
        //        $data['name'] = $data['name'] ?? '';
        if (isset($data['name'])) {
            $where = [
                ['name', 'like', '%' . $data['name'] . '%'],
                ['sold', '=', 1],
            ];
            $gift = app('model_gift')
                ->where($where)
                ->select('id')
                ->get()
                ->toArray();
            $giftIds = array_column($gift, 'id');
            $modelPro = app('model_game_product_sku')->whereIn('product_id', $giftIds);
        } else {
            $modelPro = app('model_game_product_sku');
        }


        $list = $modelPro
            ->with([
                'gift' => function ($query) use ($data) {
                    $query->select(['id', 'name']);
                },
            ])
            ->paginate($data['page_size'], ['*'], '', $data['page'])
            ->toArray();
        $result = [
            'total'        => $list['total'] ?? 0,
            'current_page' => $list['current_page'] ?? 1,
            'last_page'    => $list['last_page'] ?? 1,
            'list'         => $list['data'],
        ];

        return Response::sendData($result);
    }


    /**
     * @api {delete} /guessing/pro 删除礼物配置
     * @apiVersion 0.1.0
     * @apiName 编辑商品
     * @apiGroup 霍克城堡 竞猜
     * @apiParam {Int}                     id 商品 （必填）
     * @apiSuccessExample 成功响应
     * {"code":200,"data":true}
     * @apiErrorExample 错误响应
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     */
    public function delPro(Request $request)
    {
        $id = $request->input('id', null);
        if (empty($id)) {
            throw  new BasicException(10001);
        }
        $res = app('model_game_product_sku')
            ->where('id', $id)
            ->delete();
        if ($res) {
            return Response::sendData(true);
        } else {
            throw  new BasicException(10001, '插入失败');
        }
    }
}